import axios, {AxiosRequestConfig, AxiosResponse} from 'axios'
import {ApiRequest, ServiceKey} from './types'

interface StandardResponse<T = any> {
  code: number
  message: string
  data: T
}

function getBaseUrl(service: ServiceKey): string {
  // 非 Electron 环境下直接命中后端地址；当前仅用到 SOURCE
  if (service === 'SOURCE') return 'http://localhost:31002'
  throw new Error(`Unknown service: ${service}`)
}

export async function apiRequest<T = any>(req: ApiRequest): Promise<T> {
  // 在 Electron 环境走主进程，避免跨域
  if (typeof window !== 'undefined' && (window as any).api) {
    // 使用全局 preload 暴露的安全 API
    return window.api.request<T>(req)
  }

  // 浏览器预览环境直接走后端（需后端允许 CORS 或通过代理）
  const isDev = typeof import.meta !== 'undefined' && (import.meta as any).env?.DEV
  const config: AxiosRequestConfig = {
    // 在开发模式下，使用相对路径交由 Vite 代理处理，避免跨域
    baseURL: isDev ? undefined : getBaseUrl(req.service),
    url: req.path,
    method: req.method,
    params: req.params,
    data: req.body,
    headers: {
      'Content-Type': 'application/json',
      ...(req.headers || {}),
    },
    timeout: 30000,
  }

  try {
    const resp: AxiosResponse<StandardResponse<T> | T> = await axios.request(config)
    const payload = resp.data
    if (payload && typeof payload === 'object' && 'code' in (payload as any)) {
      const std = payload as StandardResponse<T>
      // 兼容后端返回 code=200 或 code=20000 的成功格式
      if (std.code === 200 || std.code === 20000) return std.data
      throw new Error(std.message || '请求失败')
    }
    return payload as T
  } catch (err: any) {
    if (axios.isAxiosError(err)) {
      const msg = (err.response?.data as any)?.message || err.message || '网络请求失败'
      throw new Error(msg)
    }
    throw err
  }
}